#!/usr/bin/env python
# coding: utf-8

# In[ ]:
# -*- coding: UTF-8 -*-
import requests
import tkinter as tk
url = ""
link = "http://listen.9sing.cn"
import tkinter.ttk as ttk

def get_link():
    url = inputEntry.get()
   
    responce = requests.get(url)
    string = responce.text
    print(string)
# start_mp3,end_mp3：分别表示mp3开始的字符串，结束的字符串
    start_mp3 = "var danceFilePath = '"
    end_mp3 = "';"
#start_mp4,end_mp4：分别表示mp4开始的字符串，结束的字符串
    start_mp4 = 'vMp4url    = "mp4:'
    end_mp4 = '";'
# 使用find找到地址开始的位置
    s = string.find(start_mp3)
#只要s不等于-1，说明找到了mp3格式
    if s!= -1:
    #找结束位置
        e = string.find(end_mp3, s)
    #截取地址 
        sub_str = string[s+len(start_mp3):e ]
        down_link = link+sub_str
        #print(down_link)
    #否则就是mp4格式
    else:
        s = string.find(start_mp4)
      #找结束位置
        e = string.find(end_mp4, s)
       #截取地址 
        sub_str = string[s+len(start_mp4):e ]
        down_link = link+sub_str
     # print(down_link)
    #area.insert(END,'网址错误,请榆查后再复制\n')
    #area.see(END)
    #area.update()    
#下载  
#def down_file():
    
    
    r = requests.get(down_link, stream=True)
    #以原文件名保存
    file_name = down_link.split('/')[-1]
    file = str(file_name)
    #print(file_name)
    type(file_name)
    #print('正在下载:%s'%file_name)
    
    area.insert('insert','正在下载:%s \n'%file_name)
    area.see('insert')
    area.update()
    with open(file_name, "wb") as mp4:
        for chunk in r.iter_content(chunk_size=1024 * 1024):
            if chunk:
                mp4.write(chunk) 
    #print("下载结束")
    area.insert('insert','下载结束 \n')
    area.see('insert')
    area.update()         

win=tk.Tk()
win.title("92kk音乐下载")
win.rowconfigure(1, weight=1)
win.columnconfigure(0, weight=1)
#output
outputFrame = tk.LabelFrame(win,text="Output")
outputFrame.rowconfigure(0,weight=1)
outputFrame.columnconfigure(0,weight=1)
#area = Text(outputFrame).grid(row=0,sticky=tk.NSEW)
area = tk.Text(outputFrame)
area.pack()
area.insert('insert','等待输入网址')
area.insert('insert','\n')
#print(area)
outputFrame.grid(row=1,sticky=tk.NSEW)
#setting
setFrame = tk.LabelFrame(win,text="input")
setFrame.columnconfigure(2, weight=1)
comLable = tk.Label(setFrame,text="地 址 如： ").grid(row=0,column=0)
#comSpiner = tk.Spinbox(setFrame,text="COM1").grid(row=0,column=1,sticky=tk.EW)
comLable1 = tk.Label(setFrame,text="http://www.92kk.com/play/67848.html ").grid(row=0,column=1)
#refrashButton = ttk.Button(setFrame,text="Refresh").grid(row=0,column=2,sticky=tk.EW)
inputLable = tk.Label(setFrame,text="歌曲地址： ").grid(row=1,column=0)
e=tk.StringVar()
inputEntry = tk.Entry(setFrame,textvariable=e)
inputEntry.grid(row=1,column=1,sticky=tk.EW,columnspan=2)
e.set('http://www.92kk.com/play/67848.html') 
ulr=inputEntry.get()

sendButton = ttk.Button(setFrame,text="下 载",command=get_link).grid(row=1,column=3)
setFrame.grid(row=0,sticky=tk.EW)


win.mainloop()

